package com.example.imtoken.core.utils

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.widget.ImageView
import androidx.core.content.FileProvider
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.bumptech.glide.request.RequestOptions
import com.example.imtoken.R
import java.io.File
import java.io.FileOutputStream

object MyImageLoaderUtils {

    /**
     * 加载圆形图片
     * @param context Context   上下文
     * @param imageUrl String   图片地址
     * @param imageView ImageView
     */
    fun loadRound(context: Context, imageUrl: String, imageView: ImageView) {
        val options = RequestOptions()
            .centerCrop()
            .priority(Priority.HIGH)
            .transform(GlideCircleTransform())
        Glide.with(context).load(imageUrl).error(R.mipmap.ic_launcher_round).apply(options)
            .into(imageView)
    }

    fun saveImageToGallery(bitmap: Bitmap, context: Context): Uri? {
        val storPath = "${context.getExternalFilesDir("image")}${File.separator}"
        val appDir = File(storPath)
        if (!appDir.exists()) {
        }
        appDir.mkdir()
        val fileName = "${System.currentTimeMillis()}.png"
        val file = File(appDir, fileName)
        try {
            val fos = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.PNG, 60, fos)
            fos.flush()
            fos.close()
            MediaStore.Images.Media.insertImage(
                context.contentResolver,
                file.absolutePath,
                fileName,
                null
            )
            val uri =if (Build.VERSION.SDK_INT>=24){
                FileProvider.getUriForFile(context,"com.example.imtoken.fileProvider" ,file)
            }else{
                Uri.fromFile(file)
            }
            context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_FINISHED, uri))
            return uri
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

}